package cn.yuhao.party.user.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;
import cn.yuhao.party.user.domain.User;

public class UserDao {
	private QueryRunner qr=new TxQueryRunner();
	public User login(String username,String password) throws SQLException{
		String sql="select * from Guser where Gusername=? and Gpwd=?";
	
		return qr.query(sql, new BeanHandler<User>(User.class),username,password);
	}
	public PageBean<User> findAll(int pc) {
		int ps = PageConstants.BOOK_PAGE_SIZE;//每页记录数
		String sql = "select * from Guser limit ?,?";
		try {
			String sql1 = "select count(*) from Guser";
			Number number = (Number)qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();//得到了总记录数
			List<User> listUser = qr.query(sql, new BeanListHandler<User>(
					User.class),(pc-1) * ps,ps);
			PageBean<User> pb = new PageBean<User>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listUser);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);
			
			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public void level(String username, int lev) {
		String sql="update Guser set level=level+? where Gusername=?";
		try {
			
			qr.update(sql,lev,username);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	
}
